package cn.cimoc.filter;


import cn.cimoc.model.vo.ResultVO;
import cn.cimoc.util.SpringUtils;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.cimoc.constant.ConstantPool;
import cn.cimoc.util.JwtUtils;
import cn.cimoc.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

//        String tokenHeader = request.getHeader(JwtUtils.TOKEN_HEADER);
//        // 如果请求头中没有Authorization信息则直接放行了
//        if (tokenHeader == null || !tokenHeader.startsWith(JwtUtils.TOKEN_PREFIX)) {
//            chain.doFilter(request, response);
//            return;
//        }
        // 前端没做token，借用redis模拟一下
        RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
        if (!redisUtils.hasKey(ConstantPool.FAQ)) {
            chain.doFilter(request, response);
            return;
        }
        String tokenHeader = JwtUtils.TOKEN_PREFIX + redisUtils.get(ConstantPool.FAQ);
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            UsernamePasswordAuthenticationToken authentication = getAuthentication(tokenHeader);
            assert authentication != null;
            request.setAttribute(ConstantPool.USERNAME, authentication.getPrincipal());
            request.setAttribute(ConstantPool.USER_ID, authentication.getCredentials());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (TokenExpiredException e) {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = e.getMessage();
            response.getWriter().write(new ObjectMapper().writeValueAsString(new ResultVO("error", 403, reason)));
            response.getWriter().flush();
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    /**
     * <p>
     * 这里从token中获取用户信息并新建一个UsernamePasswordAuthenticationToken
     * UsernamePasswordAuthenticationToken包含了此token的权限信息
     * @author lgz
     * @date 2021/11/21 15:15
     * @param tokenHeader :
     * @return : org.springframework.security.authentication.UsernamePasswordAuthenticationToken
     */
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenExpiredException {
        String token = tokenHeader.replace(JwtUtils.TOKEN_PREFIX, "");
        boolean expiration = JwtUtils.isExpiration(token);
        if (expiration) {
            throw new TokenExpiredException("token过期了");
        } else {
            RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
            if (!redisUtils.hasKey(token)) {
                throw new TokenExpiredException("token过期了");
            }
            DecodedJWT verify = JwtUtils.verify(token);
            String username = verify.getClaim(ConstantPool.USERNAME).asString();
            String roles = verify.getClaim(ConstantPool.ROLE).asString();
            Long uid = Long.parseLong(verify.getClaim(ConstantPool.USER_ID).asString());

            if (username != null) {
                Set<String> set = new HashSet<>();
                for (String role: roles.split(",")) {
                    set.add((String)redisUtils.get(role));
                }
                String permissions = String.join(",", set.toArray(new String[0]));
                Collection<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(permissions);
                return new UsernamePasswordAuthenticationToken(username, uid, authorities);
            }
        }
        return null;
    }

}
